﻿//-----------------------------------------------------------------------
// <copyright file="CommonPlaceListPage.xaml.cs" company="FIT VUT">
//     Copyright (c) FIT VUT. All rights are reserved.
// </copyright>
//----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using System.Device.Location;

using BookCaching.CustomControls;
using BookCaching.Data;
using BookCaching.Misc;
using BookCaching.Settings;

namespace BookCaching.Pages
{
    public partial class CommonPlaceListPage : PhoneApplicationPage
    {
        private const double EARTH_RADIUS = 6378000;
        
        public CommonPlaceListPage()
        {
            this.InitializeComponent();
        }

        private double deg_to_rad(double deg)
        {
            return deg / (180 / Math.PI);
        }

        private double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
        {
            return EARTH_RADIUS * Math.Acos(
                Math.Sin(lat1) * Math.Sin(lat2)
                + Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(lon2 - lon1));
        }

        private int CompareDistancesWithCurrentPosition(double lat1, double lon1, double lat2, double lon2)
        {

            double distance1 = CalculateDistance(CurrentSettings.Instance.CurrentPosition.Latitude, 
                CurrentSettings.Instance.CurrentPosition.Longitude, lat1, lon1);
            double distance2 = CalculateDistance(CurrentSettings.Instance.CurrentPosition.Latitude,
                CurrentSettings.Instance.CurrentPosition.Longitude, lat2, lon2);

            return distance1.CompareTo(distance2);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);

                Knihotoc_WCFService.Knihotoc_WP7ServiceClient client =
                    new Knihotoc_WCFService.Knihotoc_WP7ServiceClient();

                client.GetPlacesByAreaCompleted += client_GetPlacesByAreaCompleted;
                client.GetPlacesByAreaAsync(CurrentSettings.Instance.CurrentPosition.Latitude - CurrentSettings.Instance.Distance,
                                            CurrentSettings.Instance.CurrentPosition.Longitude - CurrentSettings.Instance.Distance,
                                            CurrentSettings.Instance.CurrentPosition.Latitude + CurrentSettings.Instance.Distance,
                                            CurrentSettings.Instance.CurrentPosition.Longitude + CurrentSettings.Instance.Distance,
                                            null);
            }
            catch
            {
                // TODO
            }

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("SettingsButtonLabel");
            ApplicationBar.BackgroundColor = CurrentSettings.Instance.ForegroundColor.Color;
        }

        void client_GetPlacesByAreaCompleted(object sender, Knihotoc_WCFService.GetPlacesByAreaCompletedEventArgs e)
        {
            List<Knihotoc_WCFService.Place> lp = e.Result.ToList();
            List<Place> placesSource = new List<Place>();

            foreach (Knihotoc_WCFService.Place p in lp)
            {
                Place place = new Place();
                if (p.Address != null)
                {
                    place.Address = new Address(p.Address);
                    place.LogoImageVisibility = CurrentSettings.Instance.PlaceIconVisibility;
                }

                place.Description = p.Description;
                place.ID = p.ID;
                place.Name = p.Name;
                place.Distance = CalculateDistance(deg_to_rad(place.Address.Lat.Value), deg_to_rad(place.Address.Lon.Value), deg_to_rad(CurrentSettings.Instance.CurrentPosition.Latitude), deg_to_rad(CurrentSettings.Instance.CurrentPosition.Longitude));
                place.DistanceString = Math.Round(place.Distance).ToString() + " m";

                placesSource.Add(place);
            }

            // sort and order ascending
            switch (CurrentSettings.Instance.PlaceListSortingBy)
            {
                case SortingPlacesBy.distance:
                    //placesSource.Sort((x, y) => CompareDistancesWithCurrentPosition(x.Lat, x.Lon, y.Lat, y.Lon));
                    placesSource.Sort((x, y) => x.Distance.CompareTo(y.Distance));
                    break;
                case SortingPlacesBy.name:
                    placesSource.Sort((x, y) => string.Compare(x.Name, y.Name));
                    break;
                default:
                    throw new ArgumentOutOfRangeException("This value of the enum is not valid!");
            }

            // order descending - just reverse list
            switch (CurrentSettings.Instance.PlaceListOrderingOrder)
            {
                case OrderingOrder.ascending:
                    break;
                case OrderingOrder.descending:
                    placesSource.Reverse();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("This value of the enum is not valid!");
            }

            commonPlacesListBox.ItemsSource = placesSource;
        }

        private void CommonPlaceItemTemplate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int placeID = ((GridID)sender).ID;

            NavigationService.Navigate(new Uri("/Pages/CommonPlaceDetailPage.xaml?PlaceID=" + placeID.ToString(), 
                UriKind.Relative));
        }

        private void SettingsApplicationBarButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/CommonPlaceListSettingsPage.xaml", UriKind.Relative));
        }
    }
}